package freebase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.io.*;

public class InsertIntoQuadruples {
	public static void main(String[] args) {
		try {
			Connection conn;
			Statement stmt;
			ResultSet res;

			Class.forName("com.mysql.jdbc.Driver").newInstance();

			conn = DriverManager.getConnection(
					"jdbc:mysql://pardosa06.cs.washington.edu/freebase",
					"clzhang", "wiki");

			stmt = conn.createStatement();

			res = stmt
					.executeQuery("select MAX(myid) AS MAXID from quadruples");
			int maxid = -1;
			while (res.next()) {
				String maxidstr = res.getString("MAXID");
				if(maxidstr!=null){
					maxid = Integer.parseInt(maxidstr);
				}
			}
			res.close();

			BufferedReader br = new BufferedReader(new FileReader(args[0]));
			String line = "";
			int ln = 1;
			int inserted = 0;
			while ((line = br.readLine()) != null) {
				if (ln <= maxid) {
					ln++;
					continue;
				}
				try {
					line = line.replaceAll("'","''");
					String[] abc = line.split("\t");
					String query = "insert into quadruples values (";
					for (int i = 0; i < abc.length; i++) {
						
						query += "'" + abc[i] + "',";
					}
					if(abc.length == 3){
						query+="'',";
					}
					query += ln + ")";
					stmt.executeUpdate(query);
					ln++;
					inserted++;
					if(inserted%100000==0)System.out.print(".");
					if(inserted%10000000==0)System.out.println();
				} catch (Exception e) {
					System.err.println(e.toString());
				}
			}

			br.close();
		} catch (Exception ex) {
			System.out.println("Error : " + ex.toString());
		}

	}
}
